<!DOCTYPE html>
<html>
<head><meta name="generator" content="Hexo 3.9.0">
    

    

    



    <meta charset="utf-8">
    
    
    
    <title>什么时候使用CountDownLatch | 奔跑的蜗牛 | 虚心若愚</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#3F51B5">
    
    
    <meta name="keywords" content="CountDownLatch">
    <meta name="description" content="原文地址译文地址：什么时候使用CountDownLatch 什么时候使用CountDownLatch正如每个Java文档所描述的那样，CountDownLatch是一个同步工具类，它允许一个或多个线程一直等待，直到其他线程的操作执行完后再执行。在Java并发中，countdownlatch的概念是一个常见的面试题，所以一定要确保你很好的理解了它。 CountDownLatch是什么CountDow">
<meta name="keywords" content="CountDownLatch">
<meta property="og:type" content="article">
<meta property="og:title" content="什么时候使用CountDownLatch">
<meta property="og:url" content="http://windynature.oschina.io/2017/04/05/java/多线程/CountDownLatch详解/index.html">
<meta property="og:site_name" content="奔跑的蜗牛">
<meta property="og:description" content="原文地址译文地址：什么时候使用CountDownLatch 什么时候使用CountDownLatch正如每个Java文档所描述的那样，CountDownLatch是一个同步工具类，它允许一个或多个线程一直等待，直到其他线程的操作执行完后再执行。在Java并发中，countdownlatch的概念是一个常见的面试题，所以一定要确保你很好的理解了它。 CountDownLatch是什么CountDow">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://windynature.oschina.io/blog/2017/04/05/java/多线程/CountDownLatch详解/countdownlatch.png">
<meta property="og:updated_time" content="2020-03-18T04:10:13.522Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="什么时候使用CountDownLatch">
<meta name="twitter:description" content="原文地址译文地址：什么时候使用CountDownLatch 什么时候使用CountDownLatch正如每个Java文档所描述的那样，CountDownLatch是一个同步工具类，它允许一个或多个线程一直等待，直到其他线程的操作执行完后再执行。在Java并发中，countdownlatch的概念是一个常见的面试题，所以一定要确保你很好的理解了它。 CountDownLatch是什么CountDow">
<meta name="twitter:image" content="http://windynature.oschina.io/blog/2017/04/05/java/多线程/CountDownLatch详解/countdownlatch.png">
    
        <link rel="alternative" href="/atom.xml" title="奔跑的蜗牛" type="application/atom+xml">
    
    <link rel="shortcut icon" href="/blog/favicon.ico">
    <link rel="stylesheet" href="//unpkg.com/hexo-theme-material-indigo@1.5.2/css/style.css">
    <script>window.lazyScripts=[]</script>
</head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu" class="hide" >
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap" style="background-image:url(/blog/img/timg.jpg)">
      <div class="brand">
        <a href="/blog/" class="avatar waves-effect waves-circle waves-light">
          <img src="/blog/img/user2.jpg">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">windy</h5>
          <a href="mailto:windynature@163.com" title="windynature@163.com" class="mail">windynature@163.com</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/blog/"  >
                <i class="icon icon-lg icon-home"></i>
                主页
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/blog/archives"  >
                <i class="icon icon-lg icon-archives"></i>
                归档
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/blog/tags"  >
                <i class="icon icon-lg icon-tags"></i>
                标签
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/blog/categories"  >
                <i class="icon icon-lg icon-th-list"></i>
                分类
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://github.com/WindyNature" target="_blank" >
                <i class="icon icon-lg icon-github"></i>
                Github
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://git.oschina.net/windynature" target="_blank" >
                <i class="icon icon-lg icon-mayun"></i>
                码云
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">什么时候使用CountDownLatch</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">什么时候使用CountDownLatch</h1>
        <h5 class="subtitle">
            
                <time datetime="2017-04-05T13:40:17.000Z" itemprop="datePublished" class="page-time">
  2017-04-05
</time>


	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/blog/categories/多线程/">多线程</a></li></ul>

            
        </h5>
    </div>

    

</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#什么时候使用CountDownLatch"><span class="post-toc-text">什么时候使用CountDownLatch</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#CountDownLatch是什么"><span class="post-toc-text">CountDownLatch是什么</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#CountDownLatch如何工作"><span class="post-toc-text">CountDownLatch如何工作</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#在实时系统中的使用场景"><span class="post-toc-text">在实时系统中的使用场景</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#1-实现最大的并行性"><span class="post-toc-text">1. 实现最大的并行性</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#2-开始执行前等待n个线程完成各自任务"><span class="post-toc-text">2. 开始执行前等待n个线程完成各自任务</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#3-死锁检测"><span class="post-toc-text">3. 死锁检测</span></a></li></ol></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#CountDownLatch使用例子"><span class="post-toc-text">CountDownLatch使用例子</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#常见面试题"><span class="post-toc-text">常见面试题</span></a></li></ol></li></ol>
        </nav>
    </aside>
    
<article id="post-java/多线程/CountDownLatch详解"
  class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">什么时候使用CountDownLatch</h1>
        <div class="post-meta">
            <time class="post-time" title="2017年04月05日 21:40" datetime="2017-04-05T13:40:17.000Z"  itemprop="datePublished">2017-04-05</time>

            
	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/blog/categories/多线程/">多线程</a></li></ul>



            
<span id="busuanzi_container_page_pv" title="文章总阅读量" style='display:none'>
    <i class="icon icon-eye icon-pr"></i><span id="busuanzi_value_page_pv"></span>
</span>


            

        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <p><a href="http://howtodoinjava.com/core-java/multi-threading/when-to-use-countdownlatch-java-concurrency-example-tutorial/" target="_blank" rel="noopener">原文地址</a><br><a href="http://howtodoinjava.com/core-java/multi-threading/when-to-use-countdownlatch-java-concurrency-example-tutorial/" target="_blank" rel="noopener">译文地址：什么时候使用CountDownLatch</a></p>
<h1 id="什么时候使用CountDownLatch"><a href="#什么时候使用CountDownLatch" class="headerlink" title="什么时候使用CountDownLatch"></a>什么时候使用CountDownLatch</h1><p>正如每个Java文档所描述的那样，<code>CountDownLatch</code>是一个<code>同步工具类</code>，<strong>它允许一个或多个线程一直等待，直到其他线程的操作执行完后再执行</strong>。在Java并发中，countdownlatch的概念是一个常见的面试题，所以一定要确保你很好的理解了它。</p>
<h2 id="CountDownLatch是什么"><a href="#CountDownLatch是什么" class="headerlink" title="CountDownLatch是什么"></a>CountDownLatch是什么</h2><p><code>CountDownLatch</code>是在java1.5被引入的，跟它一起被引入的并发工具类还有<code>CyclicBarrier</code>、<code>Semaphore</code>、<code>ConcurrentHashMap</code>和<code>BlockingQueue</code>，它们都存在于<code>java.util.concurrent</code>包下。<code>CountDownLatch</code>这个类<strong>能够使一个线程等待其他线程完成各自的工作后再执行</strong>。例如，应用程序的主线程希望在负责启动框架服务的线程已经启动所有的框架服务之后再执行。</p>
<p><code>CountDownLatch</code>是通过一个计数器来实现的，计数器的初始值为线程的数量。当一个线程完成了自己的任务后，计数器的值就会减1。当计数器值到达0时，它表示所有的线程已经完成了任务，然后在闭锁上等待的线程就可以恢复执行任务。</p>
<figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="/blog/2017/04/05/java/多线程/CountDownLatch详解/countdownlatch.png" alt="countdownlatch" title>
                </div>
                <div class="image-caption">countdownlatch</div>
            </figure>

<p>CountDownLatch的伪代码如下所示:</p>
<blockquote>
<p>Main thread start<br>Create CountDownLatch for N threads<br>Create and start N threads<br>Main thread wait on latch<br>N threads completes there tasks are returns<br>Main thread resume execution</p>
</blockquote>
<h2 id="CountDownLatch如何工作"><a href="#CountDownLatch如何工作" class="headerlink" title="CountDownLatch如何工作"></a>CountDownLatch如何工作</h2><p>CountDownLatch.java类中定义的构造函数：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//Constructs a CountDownLatch initialized with the given count.</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">CountDownLatch</span><span class="params">(<span class="keyword">int</span> count)</span> </span>&#123;...&#125;</span><br></pre></td></tr></table></figure>

<p>构造器中的<strong>计数值（count）实际上就是闭锁需要等待的线程数量</strong>。这个值<code>只能被设置一次</code>，而且<code>CountDownLatch</code><strong>没有提供任何机制去重新设置这个计数值</strong>。</p>
<p>与<code>CountDownLatch</code>的第一次交互是<strong>主线程等待其他线程。</strong>主线程必须在启动其他线程后立即调用<strong><code>CountDownLatch.await()</code></strong>方法。这样主线程的操作就会在这个方法上阻塞，知道其他线程完成各自的任务。</p>
<p>其他N个线程<strong>必须引用闭锁对象</strong>，因为他们要通知CountDownLatch对象，他们已经完成了各自的任务。这种通知机制是通过<code>CounDownLatch.countDown()</code>方法来完成的；每调用一次这个方法，在这个构造函数中的初始化的count值就减1。所以当N个线程都调用了这个方法，count的值等于0，然后主线程就能通过<code>await()</code>方法，恢复执行自己的任务。</p>
<h2 id="在实时系统中的使用场景"><a href="#在实时系统中的使用场景" class="headerlink" title="在实时系统中的使用场景"></a>在实时系统中的使用场景</h2><h3 id="1-实现最大的并行性"><a href="#1-实现最大的并行性" class="headerlink" title="1. 实现最大的并行性"></a>1. 实现最大的并行性</h3><p>有事我们想同事启动多个线程，实现最大程度的并行性。例如，我们想测试一个单例类。如果我们创建一个初始计数为1的<code>CountDownLatch</code>，并让所有线程都在这个锁上等待，那么我们可以很轻松地完成测试。我们只需调用一次<code>countDown()</code>方法就可以让所有的等待线程同时恢复执行。</p>
<h3 id="2-开始执行前等待n个线程完成各自任务"><a href="#2-开始执行前等待n个线程完成各自任务" class="headerlink" title="2. 开始执行前等待n个线程完成各自任务"></a>2. 开始执行前等待n个线程完成各自任务</h3><p>例如应用程序启动类要确保在处理用户请求前，所有N个外部系统已经启动和运行了。</p>
<h3 id="3-死锁检测"><a href="#3-死锁检测" class="headerlink" title="3. 死锁检测"></a>3. 死锁检测</h3><p>一个非常方便的使用场景，你可以使用n个线程访问共享资源，在每次测试阶段的线程数目是不同的，并尝试产生死锁。</p>
<h2 id="CountDownLatch使用例子"><a href="#CountDownLatch使用例子" class="headerlink" title="CountDownLatch使用例子"></a>CountDownLatch使用例子</h2><p>在这个例子中，我模拟了一个应用程序启动类，它开始启动了n个线程，这些线程将检查外部系统并通知闭锁，并且启动类一直在闭锁上等待着。一旦验证和检查了所有外部服务，那么启动类恢复执行。</p>
<p><code>BaseHealthChecker.java</code>：这个类是一个Runnable，负责所有特定的外部服务健康的检测。它删除了重复的代码和闭锁的中心控制代码。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">BaseHandlerChecker</span> <span class="keyword">implements</span> <span class="title">Runnable</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> CountDownLatch _latch;</span><br><span class="line">    <span class="keyword">private</span> String _serviceName;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">boolean</span> _serviceUp;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//Get latch object in constructor so that after completing the task, thread can countdown() the latch</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">BaseHandlerChecker</span><span class="params">(String serviceName,CountDownLatch latch)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>();</span><br><span class="line">        <span class="keyword">this</span>._latch = latch;</span><br><span class="line">        <span class="keyword">this</span>._serviceName = serviceName;</span><br><span class="line">        <span class="keyword">this</span>._serviceUp = <span class="keyword">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            verifyService();</span><br><span class="line">            _serviceUp = <span class="keyword">true</span>;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Throwable t) &#123;</span><br><span class="line">            t.printStackTrace(System.err);</span><br><span class="line">            _serviceUp = <span class="keyword">false</span>;</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            <span class="keyword">if</span>(_latch!=<span class="keyword">null</span>) &#123;</span><br><span class="line">                _latch.countDown();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getServiceName</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> _serviceName;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isServiceUp</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> _serviceUp;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//This methos needs to be implemented by all specific service checker</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">void</span> <span class="title">verifyService</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>NetworkHealthChecker.java</code>：这个类继承了BaseHealthChecker，实现了verifyService()方法。DatabaseHealthChecker.java和CacheHealthChecker.java除了服务名和休眠时间外，与NetworkHealthChecker.java是一样的。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">NetworkHealthChecker</span> <span class="keyword">extends</span> <span class="title">BaseHealthChecker</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">NetworkHealthChecker</span> <span class="params">(CountDownLatch latch)</span>  </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>(<span class="string">"Network Service"</span>, latch);</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">verifyService</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"Checking "</span> + <span class="keyword">this</span>.getServiceName());</span><br><span class="line">        <span class="keyword">try</span></span><br><span class="line">        &#123;</span><br><span class="line">            Thread.sleep(<span class="number">7000</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">catch</span> (InterruptedException e)</span><br><span class="line">        &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(<span class="keyword">this</span>.getServiceName() + <span class="string">" is UP"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>ApplicationStartupUtil.java</code>：这个类是一个主启动类，它负责初始化闭锁，然后等待，直到所有服务都被检测完。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ApplicationStartupUtil</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    <span class="comment">//List of service checkers</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> List&lt;BaseHealthChecker&gt; _services;</span><br><span class="line"> </span><br><span class="line">    <span class="comment">//This latch will be used to wait on</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> CountDownLatch _latch;</span><br><span class="line"> </span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="title">ApplicationStartupUtil</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> ApplicationStartupUtil INSTANCE = <span class="keyword">new</span> ApplicationStartupUtil();</span><br><span class="line"> </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> ApplicationStartupUtil <span class="title">getInstance</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> INSTANCE;</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">boolean</span> <span class="title">checkExternalServices</span><span class="params">()</span> <span class="keyword">throws</span> Exception</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="comment">//Initialize the latch with number of service checkers</span></span><br><span class="line">        _latch = <span class="keyword">new</span> CountDownLatch(<span class="number">3</span>);</span><br><span class="line"> </span><br><span class="line">        <span class="comment">//All add checker in lists</span></span><br><span class="line">        _services = <span class="keyword">new</span> ArrayList&lt;BaseHealthChecker&gt;();</span><br><span class="line">        _services.add(<span class="keyword">new</span> NetworkHealthChecker(_latch));</span><br><span class="line">        _services.add(<span class="keyword">new</span> CacheHealthChecker(_latch));</span><br><span class="line">        _services.add(<span class="keyword">new</span> DatabaseHealthChecker(_latch));</span><br><span class="line"> </span><br><span class="line">        <span class="comment">//Start service checkers using executor framework</span></span><br><span class="line">        Executor executor = Executors.newFixedThreadPool(_services.size());</span><br><span class="line"> </span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">final</span> BaseHealthChecker v : _services)</span><br><span class="line">        &#123;</span><br><span class="line">            executor.execute(v);</span><br><span class="line">        &#125;</span><br><span class="line"> </span><br><span class="line">        <span class="comment">//Now wait till all services are checked</span></span><br><span class="line">        _latch.await();</span><br><span class="line"> </span><br><span class="line">        <span class="comment">//Services are file and now proceed startup</span></span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">final</span> BaseHealthChecker v : _services)</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">if</span>( ! v.isServiceUp())</span><br><span class="line">            &#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>现在你可以写测试代码去检测一下闭锁的功能了。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Main</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">boolean</span> result = <span class="keyword">false</span>;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            result = ApplicationStartupUtil.checkExternalServices();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(<span class="string">"External services validation completed !! Result was :: "</span>+ result);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>结果：</strong></p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">Output in console:</span><br><span class="line"> </span><br><span class="line">Checking Network Service</span><br><span class="line">Checking Cache Service</span><br><span class="line">Checking Database Service</span><br><span class="line">Database Service is UP</span><br><span class="line">Cache Service is UP</span><br><span class="line">Network Service is UP</span><br><span class="line">External services validation completed !! Result was :: true</span><br></pre></td></tr></table></figure>

<h2 id="常见面试题"><a href="#常见面试题" class="headerlink" title="常见面试题"></a>常见面试题</h2><ul>
<li>解释一下CountDownLatch概念?</li>
<li>CountDownLatch 和CyclicBarrier的不同之处?</li>
<li>给出一些CountDownLatch使用的例子?</li>
<li>CountDownLatch 类中主要的方法?</li>
</ul>

        </div>

        <blockquote class="post-copyright">
    <div class="content">
        
<span class="post-time">
    最后更新时间：<time datetime="2020-03-18T04:10:13.522Z" itemprop="dateUpdated">2020年3月18日 12:10</time>
</span><br>


        这里写留言或版权声明：<a href="/blog/2017/04/05/java/多线程/CountDownLatch详解/" target="_blank" rel="external">http://windynature.oschina.io/2017/04/05/java/多线程/CountDownLatch详解/</a>
    </div>
    <footer>
        <a href="http://windynature.oschina.io">
            <img src="/blog/img/user2.jpg" alt="windy">
            windy
        </a>
    </footer>
</blockquote>

        


        <div class="post-footer">
            
	<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/blog/tags/CountDownLatch/">CountDownLatch</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://windynature.oschina.io/2017/04/05/java/多线程/CountDownLatch详解/&title=《什么时候使用CountDownLatch》 — 奔跑的蜗牛&pic=http://windynature.oschina.io/img/user2.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://windynature.oschina.io/2017/04/05/java/多线程/CountDownLatch详解/&title=《什么时候使用CountDownLatch》 — 奔跑的蜗牛&source=" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://windynature.oschina.io/2017/04/05/java/多线程/CountDownLatch详解/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《什么时候使用CountDownLatch》 — 奔跑的蜗牛&url=http://windynature.oschina.io/2017/04/05/java/多线程/CountDownLatch详解/&via=http://windynature.oschina.io" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://windynature.oschina.io/2017/04/05/java/多线程/CountDownLatch详解/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/blog/2017/04/12/java/多线程/创建线程的第三种方式（使用Callable和Future创建线程）/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">创建线程的第三种方式</h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/blog/2017/04/04/java/STOMP协议详解/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">STOMP协议详解</h4>
      </a>
    </div>
  
</nav>



    

<div class="comments" id="comments">
    <div class="ds-thread" data-thread-key="java/多线程/CountDownLatch详解" data-title="什么时候使用CountDownLatch" data-url="http://windynature.oschina.io/2017/04/05/java/多线程/CountDownLatch详解/"></div>
</div>
<script>
lazyScripts.push('//cdn.bootcss.com/marked/0.3.6/marked.min.js');

var duoshuoQuery = {short_name:'ysblog', theme: 'none'};
lazyScripts.push('//unpkg.com/hexo-theme-material-indigo@1.5.2/js/embed.min.js');


</script>










</article>



</div>

        <footer class="footer">
    <div class="top">
        
<p>
    <span id="busuanzi_container_site_uv" style='display:none'>
        站点总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style='display:none'>
        站点总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            <span><a href="/atom.xml" target="_blank" class="rss" title="rss"><i class="icon icon-lg icon-rss"></i></a></span>
            <span>博客内容遵循 <a href="http://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">知识共享 署名 - 非商业性 - 相同方式共享 4.0协议</a></span>
        </p>
    </div>
    <div class="bottom">
        <p>
            <span>Power by <a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="https://github.com/yscoder/hexo-theme-indigo" target="_blank">indigo</a></span>
            <span>奔跑的蜗牛 &copy; 2015 - 2020</span>
        </p>
    </div>
</footer>

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://windynature.oschina.io/2017/04/05/java/多线程/CountDownLatch详解/&title=《什么时候使用CountDownLatch》 — 奔跑的蜗牛&pic=http://windynature.oschina.io/img/user2.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://windynature.oschina.io/2017/04/05/java/多线程/CountDownLatch详解/&title=《什么时候使用CountDownLatch》 — 奔跑的蜗牛&source=" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://windynature.oschina.io/2017/04/05/java/多线程/CountDownLatch详解/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《什么时候使用CountDownLatch》 — 奔跑的蜗牛&url=http://windynature.oschina.io/2017/04/05/java/多线程/CountDownLatch详解/&via=http://windynature.oschina.io" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://windynature.oschina.io/2017/04/05/java/多线程/CountDownLatch详解/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/blog/', SHARE: true, REWARD: false };



</script>

<script src="//unpkg.com/hexo-theme-material-indigo@1.5.2/js/main.min.js"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="//unpkg.com/hexo-theme-material-indigo@1.5.2/js/search.min.js" async></script>






<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>





</body>
</html>
